package com.wrx.swing.panel.generate;

import com.wrx.service.generatesql.GenerateService;
import com.wrx.swing.form.AddDevicePointFormFields;
import com.wrx.util.SwingComponentUtil;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;

/**
 * 增加设备点位面板
 */
public class AddDevicePointPanel {

    private final GenerateService generateService;
    private final JFrame parentFrame;

    public AddDevicePointPanel(GenerateService generateService, JFrame parentFrame) {
        this.generateService = generateService;
        this.parentFrame = parentFrame;
    }

    public JPanel createPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表单字段管理对象
        AddDevicePointFormFields formFields = new AddDevicePointFormFields();

        // 创建输入面板
        JPanel inputPanel = createInputPanel(formFields);

        // 创建日志区域
        JScrollPane scrollPane = SwingComponentUtil.createLogArea(formFields.logArea);

        // 创建生成按钮
        JButton generateBtn = new JButton("生成");

        // 绑定生成事件
        setupAction(generateBtn, formFields);

        // 组装面板
        panel.add(inputPanel, BorderLayout.NORTH);
        panel.add(generateBtn, BorderLayout.CENTER);
        panel.add(scrollPane, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 创建增加设备点位输入面板
     */
    private JPanel createInputPanel(AddDevicePointFormFields fields) {
        JPanel inputPanel = SwingComponentUtil.createInputPanel("参数输入", 1, 2);

        // 添加文件选择按钮
        JButton chooseFileBtn = new JButton("选择文件");
        inputPanel.add(chooseFileBtn);
        inputPanel.add(fields.filePathField);

        // 绑定文件选择事件
        chooseFileBtn.addActionListener(e ->
            SwingComponentUtil.openFileChooser(parentFrame, fields.filePathField, fields.logArea)
        );

        return inputPanel;
    }

    /**
     * 设置增加设备点位生成事件
     */
    private void setupAction(JButton generateBtn, AddDevicePointFormFields fields) {
        generateBtn.addActionListener(e -> {
            try {
                // 验证文件
                File file = SwingComponentUtil.validateFile(fields.getFilePath(), fields.logArea);
                if (file == null) return;

                // 调用服务生成
                String result = executeAddDevicePoint(file);

                // 显示结果
                SwingComponentUtil.logSuccess(fields.logArea, "生成完成！");
                fields.logArea.append(result + "\n");

                // 确认保存
                SwingComponentUtil.confirmAndSave(parentFrame, result, "device_point.txt", fields.logArea);

            } catch (Exception ex) {
                SwingComponentUtil.logError(fields.logArea, "执行失败", ex);
            }
        });
    }

    /**
     * 执行增加设备点位
     */
    private String executeAddDevicePoint(File file) throws Exception {
        try (FileInputStream fis = new FileInputStream(file)) {
            return generateService.addDevicePointByInputStream(fis);
        }
    }
}

